/**
 * Created by lenovo on 2017/3/20.
 */
import {DataSource} from "../../../model/DataModel"
import HttpRequest from "../../../model/HttpRequset";

export default {
  mounted(){
    HttpRequest.requestSourceList().then( (response) =>{
      this.dataSource.sourceList = response.data.ds
    }).catch( (response) =>{
      this.$notify.error({title: '错误',message: "获取数据库列表失败",duration:2000,offset: 200});
    });
  },

  watch: {
    'step.connection'(newVal,oldVal){
      if (newVal && typeof newVal !== "object") {
        HttpRequest.requestSourceInstanceById(newVal).then((response) =>{
          this.dataSource.tables = response.data;
          if(!this.firstLoad){

            this.step.table="";}
        }).catch((response)=> {
          this.dataSource.tables = [];this.step.table="";
          this.$notify.error({title: '错误',message: "获取table列表失败",duration:2000,offset: 200});
        });
      }
    }
  },
  computed: {
    selectedTable(){
      let table = this.step.table, filteredList = this.dataSource.tables.filter(el =>el.name == table);
      if (filteredList.length > 0)
        return filteredList[0];
      else
        return "";
    },
  },
  data(){
    return {
      dataSource: DataSource(),
      firstLoad: true,
      rules: {
        connection: [
          {required: true, message: '请选择数据库', trigger: 'change'},
        ],
        table: [
          {required: true, message: '请选择一张表', trigger: 'change'},
        ]
      }
    }
  },
  methods:{
    //获取字段
    fetchFieldsFromTable(transPortFields){
      let table = this.selectedTable, unique = {};
      if (table && table.columnList) {
        //从availableFields中获取对象添加到unique
        this.step.availableFields.forEach(el => {
          let dotIndex = el.name.indexOf(".") + 1, tempName = el.name;
          if (dotIndex > 0) {
            tempName = el.name.substring(dotIndex);
          }
          unique[tempName.toUpperCase()] = el.name;
        });
        if(typeof transPortFields ==="function")
          transPortFields(unique,table);
      } else {
        this.$refs.form.validate();
      }
    },
  }
}
